'use client'

import { Fragment, useState } from 'react'
import { Dialog, Transition } from '@headlessui/react'
import { useForm, useFieldArray } from 'react-hook-form'
import { createInbound } from '@/actions/inbound'
import { FormInput, FormSelect } from '@/components/ui/form'
import { useSuppliers } from '@/hooks/use-suppliers'
import { useProducts } from '@/hooks/use-products'
import { PlusIcon, TrashIcon } from '@heroicons/react/24/outline'

interface CreateInboundDialogProps {
  open: boolean
  onClose: () => void
}

interface InboundFormData {
  supplierId: string
  items: {
    productId: string
    quantity: string
    price: string
  }[]
}

export function CreateInboundDialog({ open, onClose }: CreateInboundDialogProps) {
  const { suppliers, loading: loadingSuppliers } = useSuppliers()
  const { products, loading: loadingProducts } = useProducts()
  const [submitting, setSubmitting] = useState(false)

  const { register, control, handleSubmit, reset, formState: { errors } } = useForm<InboundFormData>({
    defaultValues: {
      supplierId: '',
      items: [{ productId: '', quantity: '', price: '' }]
    }
  })

  const { fields, append, remove } = useFieldArray({
    control,
    name: "items"
  })

  const onSubmit = async (data: InboundFormData) => {
    try {
      setSubmitting(true)
      const result = await createInbound(data)
      if (result.success) {
        reset()
        onClose()
      } else {
        alert(result.error)
      }
    } catch (error) {
      console.error('创建入库单失败:', error)
      alert('创建入库单失败')
    } finally {
      setSubmitting(false)
    }
  }

  return (
    <Transition show={open} as={Fragment}>
      <Dialog onClose={onClose} className="relative z-50">
        <Transition.Child
          as={Fragment}
          enter="ease-out duration-300"
          enterFrom="opacity-0"
          enterTo="opacity-100"
          leave="ease-in duration-200"
          leaveFrom="opacity-100"
          leaveTo="opacity-0"
        >
          <div className="fixed inset-0 bg-black/30" />
        </Transition.Child>

        <div className="fixed inset-0 overflow-y-auto">
          <div className="flex min-h-full items-center justify-center p-4">
            <Transition.Child
              as={Fragment}
              enter="ease-out duration-300"
              enterFrom="opacity-0 scale-95"
              enterTo="opacity-100 scale-100"
              leave="ease-in duration-200"
              leaveFrom="opacity-100 scale-100"
              leaveTo="opacity-0 scale-95"
            >
              <Dialog.Panel className="w-full max-w-2xl transform overflow-hidden rounded-lg bg-white shadow-xl transition-all">
                <div className="border-b border-gray-200 bg-white px-6 py-4">
                  <Dialog.Title as="h3" className="text-lg font-medium text-gray-900">
                    新建入库单
                  </Dialog.Title>
                </div>

                <form onSubmit={handleSubmit(onSubmit)}>
                  <div className="bg-white px-6 py-6 space-y-6">
                    {/* 供应商选择 */}
                    <FormSelect
                      label="供应商"
                      error={errors.supplierId?.message}
                      disabled={loadingSuppliers}
                      {...register('supplierId', { required: '请选择供应商' })}
                    >
                      <option value="">请选择供应商</option>
                      {suppliers?.map((supplier) => (
                        <option key={supplier.id} value={supplier.id}>
                          {supplier.name}
                        </option>
                      ))}
                    </FormSelect>

                    {/* 商品列表 */}
                    <div className="space-y-4">
                      <div className="flex justify-between items-center">
                        <h4 className="text-sm font-medium text-gray-700">商品列表</h4>
                        <button
                          type="button"
                          onClick={() => append({ productId: '', quantity: '', price: '' })}
                          className="inline-flex items-center text-sm font-medium text-blue-600 hover:text-blue-500"
                        >
                          <PlusIcon className="h-4 w-4 mr-1" />
                          添加商品
                        </button>
                      </div>

                      {fields.map((field, index) => (
                        <div key={field.id} className="flex gap-4 items-start">
                          <div className="flex-1">
                            <FormSelect
                              label="商品"
                              error={errors.items?.[index]?.productId?.message}
                              disabled={loadingProducts}
                              {...register(`items.${index}.productId`, { required: '请选择商品' })}
                            >
                              <option value="">请选择商品</option>
                              {products?.map((product) => (
                                <option key={product.id} value={product.id}>
                                  {product.name} ({product.code})
                                </option>
                              ))}
                            </FormSelect>
                          </div>
                          <div className="w-32">
                            <FormInput
                              type="number"
                              label="数量"
                              error={errors.items?.[index]?.quantity?.message}
                              {...register(`items.${index}.quantity`, { 
                                required: '请输入数量',
                                min: { value: 1, message: '数量必须大于0' }
                              })}
                            />
                          </div>
                          <div className="w-32">
                            <FormInput
                              type="number"
                              label="单价"
                              error={errors.items?.[index]?.price?.message}
                              {...register(`items.${index}.price`, { 
                                required: '请输入单价',
                                min: { value: 0, message: '单价必须大于等于0' }
                              })}
                            />
                          </div>
                          <button
                            type="button"
                            onClick={() => remove(index)}
                            className="mt-8 text-gray-400 hover:text-red-500"
                          >
                            <TrashIcon className="h-5 w-5" />
                          </button>
                        </div>
                      ))}
                    </div>
                  </div>

                  <div className="border-t border-gray-200 bg-gray-50 px-6 py-4 flex justify-end gap-4">
                    <button
                      type="button"
                      onClick={onClose}
                      className="inline-flex justify-center rounded-md border border-gray-300 bg-white px-4 py-2 text-sm font-medium text-gray-700 shadow-sm hover:bg-gray-50 focus:outline-none focus:ring-2 focus:ring-blue-500 focus:ring-offset-2"
                    >
                      取消
                    </button>
                    <button
                      type="submit"
                      disabled={submitting}
                      className="inline-flex justify-center rounded-md border border-transparent bg-blue-600 px-4 py-2 text-sm font-medium text-white shadow-sm hover:bg-blue-700 focus:outline-none focus:ring-2 focus:ring-blue-500 focus:ring-offset-2 disabled:opacity-50"
                    >
                      {submitting ? '提交中...' : '创建'}
                    </button>
                  </div>
                </form>
              </Dialog.Panel>
            </Transition.Child>
          </div>
        </div>
      </Dialog>
    </Transition>
  )
} 